package com.framework.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.framework.dao.BenefitDayDao;
import com.framework.entity.sys.SysAgent;
import com.framework.entity.tran.TranBenefitDay;
import com.framework.entity.tran.TranTerBenefitInfo;
import com.framework.entity.tran.TranTransactionInfo;
import com.framework.exception.RRException;
import com.framework.page.PageUtils;
import com.framework.redis.util.RedisUtil;
import com.framework.service.BenefitDayService;
import com.framework.service.BenefitInfoService;
import com.framework.utils.excel.ExcelUtil;
import com.framework.utils.string.StringUtil;
import com.framework.view.DividedSumDto;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 日分润汇总业务层实现
 *
 * @author wq
 */
@Transactional(rollbackFor = Exception.class)
@Service("benefitDayService")
public class BenefitDayServiceImpl extends ServiceImpl<BenefitDayDao, TranBenefitDay> implements BenefitDayService {
    @Autowired
    private BenefitInfoService benefitInfoService;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public DividedSumDto queryTransMonthSum(String lastMonth, String lastTwoMonth, Long agentId, String types) {
        return baseMapper.queryTransMonthSum(lastMonth, lastTwoMonth, agentId, types);
    }

    @Override
    public BigDecimal getThisMonthAmount(Long agentIds, Integer types) {
        return baseMapper.getThisMonthAmount(agentIds, types);
    }

    @Override
    public BigDecimal getDayAmount(Long agentId, Integer types, String datTime) {
        return baseMapper.getDayAmount(agentId, types, datTime);
    }

    @Override
    public BigDecimal getMonthAmount(Long agentId, Integer types, String monthTime) {
        return baseMapper.getMonthAmount(agentId, types, monthTime);
    }

    @Override
    public PageUtils queryListByAgentId(Map<String, Object> params) {
        Object startDate = params.get("startDate");
        Object endDate = params.get("endDate");
        if (startDate == null || "".equals(startDate)) {
            params.put("startDate", null);
        }
        if (endDate == null || "".equals(endDate)) {
            params.put("endDate", null);
        }
        Integer pageSize = Integer.valueOf(params.get("limit").toString());
        Integer currPage = Integer.valueOf(params.get("page").toString());
        params.put("start", (currPage - 1) * pageSize);
        params.put("limit", pageSize);
        List<Map<String, Object>> list = baseMapper.queryListByAgentId(params);
        Integer totalCount = baseMapper.queryCountByAgentId(params);
        redisUtil.set("benefitDown", params, 5 * 60);
        return new PageUtils(list, totalCount, pageSize, currPage);
    }

    @Override
    public void addSelfBenefitDay(TranTransactionInfo tranTransactionInfo, BigDecimal benefitAmount, SysAgent agent) {


        //查询是否有记录
        TranBenefitDay benefitDay = new TranBenefitDay();
        benefitDay.setDeptId(agent.getDeptId());
        benefitDay.setAgentId(agent.getAgentId());
        benefitDay.setBenefitDate(tranTransactionInfo.getTransactionDate());
        TranBenefitDay t = baseMapper.selectOne(benefitDay);
        String no;
        //没有则添加
        if (t == null) {

            no = StringUtil.getDateString(4);
            TranBenefitDay ter = baseMapper.selectById(no);
            if (ter != null) {
                no = StringUtil.getDateString(4);
            }
            //添加
            t = new TranBenefitDay();
            t.setBenefitId(no);
            t.setAgentId(agent.getAgentId());
            t.setDeptId(agent.getDeptId());
            t.setSelfTran(tranTransactionInfo.getAmount());
            t.setSelfAmount(benefitAmount);
            t.setAllTran(tranTransactionInfo.getAmount());
            t.setAllAmount(benefitAmount);
            t.setTeamAmount(new BigDecimal("0.00"));
            t.setTeamTran(new BigDecimal("0.00"));
            t.setBenefitDate(tranTransactionInfo.getTransactionDate());
            t.setCreateDate(new Date());
            baseMapper.insert(t);

        } else {//有则新增金额，作修改
            BigDecimal selfTran = t.getSelfTran();
            BigDecimal selfAmount = t.getSelfAmount();
            BigDecimal allTran = t.getAllTran();
            BigDecimal allAmount = t.getAllAmount();
            selfTran = selfTran.add(tranTransactionInfo.getAmount());
            selfAmount = selfAmount.add(benefitAmount);
            allTran = allTran.add(tranTransactionInfo.getAmount());
            allAmount = allAmount.add(benefitAmount);
            t.setSelfAmount(selfAmount);
            t.setSelfTran(selfTran);
            t.setAllAmount(allAmount);
            t.setAllTran(allTran);
            t.setCreateDate(new Date());
            baseMapper.updatebenefitDay(t);
            no = t.getBenefitId();

        }

        benefitInfoService.addSelfBenefitInfo(tranTransactionInfo, benefitAmount, agent, no);
    }

    @Override
    public void updateTeamTranDay(SysAgent sysAgent, TranTerBenefitInfo tranTerBenefitInfo, BigDecimal teambenefit, Date benefitDate) {


        //查询是否有记录
        TranBenefitDay benefitDay = new TranBenefitDay();
        benefitDay.setDeptId(sysAgent.getDeptId());
        benefitDay.setAgentId(sysAgent.getAgentId());
        benefitDay.setBenefitDate(benefitDate);
        TranBenefitDay t = baseMapper.selectOne(benefitDay);
        String no;
        if (t == null) {
            no = verifyBenefitNo(StringUtil.getDateString(4));
            //添加
            t = new TranBenefitDay();
            t.setBenefitId(no);
            t.setAgentId(sysAgent.getAgentId());
            t.setDeptId(sysAgent.getDeptId());
            t.setSelfTran(new BigDecimal("0.00"));
            t.setSelfAmount(new BigDecimal("0.00"));
            t.setTeamTran(tranTerBenefitInfo.getTranAmount());
            t.setTeamAmount(teambenefit);
            t.setAllTran(tranTerBenefitInfo.getTranAmount());
            t.setAllAmount(teambenefit);
            t.setBenefitDate(benefitDate);
            t.setCreateDate(new Date());
            baseMapper.insert(t);
        } else {
            //如果为空
            if (t.getTeamAmount() == null) {
                t.setTeamAmount(new BigDecimal("0.00"));
            }
            if (t.getTeamTran() == null) {
                t.setTeamTran(new BigDecimal("0.00"));
            }
            BigDecimal teamTran = t.getTeamTran().add(tranTerBenefitInfo.getTranAmount());
            BigDecimal teamAmount = t.getTeamAmount().add(teambenefit);
            BigDecimal allAmount = t.getAllAmount().add(teambenefit);
            BigDecimal alltran = t.getAllTran().add(tranTerBenefitInfo.getTranAmount());
            t.setTeamTran(teamTran);
            t.setTeamAmount(teamAmount);
            t.setAllTran(alltran);
            t.setAllAmount(allAmount);
            //更新
            baseMapper.updatebenefitDay(t);
        }
        benefitInfoService.updateTeamTranInfo(tranTerBenefitInfo, teambenefit, sysAgent, t.getBenefitId());

    }

    private String verifyBenefitNo(String no) {

        TranBenefitDay ter = baseMapper.selectById(no);
        if (ter != null) {
            no = StringUtil.getDateString(4);
            verifyBenefitNo(no);
        }
        return no;
    }

    @Override
    public void updateTeamBenefitDay(SysAgent sysAgent, TranTerBenefitInfo info, BigDecimal benefitAmount, Date benefitDate) {


        //查询是否有记录
        TranBenefitDay benefitDay = new TranBenefitDay();
        benefitDay.setDeptId(sysAgent.getDeptId());
        benefitDay.setAgentId(sysAgent.getAgentId());
        benefitDay.setBenefitDate(benefitDate);
        TranBenefitDay t = baseMapper.selectOne(benefitDay);
        String no;
        if (t == null) {
            no = verifyBenefitNo(StringUtil.getDateString(4));
            //添加
            t = new TranBenefitDay();
            t.setBenefitId(no);
            t.setAgentId(sysAgent.getAgentId());
            t.setDeptId(sysAgent.getDeptId());
            t.setSelfAmount(new BigDecimal("0.00"));
            t.setTeamAmount(benefitAmount);
            t.setAllAmount(benefitAmount);
            t.setBenefitDate(benefitDate);
            t.setCreateDate(new Date());
            baseMapper.insert(t);
        } else {
            //如果为空
            if (t.getTeamAmount() == null) {
                t.setTeamAmount(new BigDecimal("0.00"));
            }

            BigDecimal teamAmount = t.getTeamAmount().add(benefitAmount);
            BigDecimal allAmount = t.getAllAmount().add(benefitAmount);
            t.setTeamAmount(teamAmount);
            t.setAllAmount(allAmount);
            //更新
            baseMapper.updatebenefitDay(t);
        }
        benefitInfoService.updateTeamBenefitInfo(info, benefitAmount, sysAgent, t.getBenefitId());
    }

    @Override
    public List<TranBenefitDay> queryToAddFlowAccount(String benefitDateStr) {
        return baseMapper.queryToAddFlowAccount(benefitDateStr);
    }

    @Override
    public List<TranBenefitDay> queryReback(Long deptId, Date date) {

        return baseMapper.queryReback(deptId, date);
    }

    @Override
    public void addTeamBenefit(TranTransactionInfo info, SysAgent pAgent, BigDecimal pidBenefit) {


        //查询是否有记录
        TranBenefitDay benefitDay = new TranBenefitDay();
        benefitDay.setDeptId(pAgent.getDeptId());
        benefitDay.setAgentId(pAgent.getAgentId());
        benefitDay.setBenefitDate(info.getTransactionDate());
        TranBenefitDay t = baseMapper.selectOne(benefitDay);
        String no;
        if (t == null) {
            no =verifyBenefitNo(StringUtil.getDateString(4));
            //添加
            t = new TranBenefitDay();
            t.setBenefitId(no);
            t.setAgentId(pAgent.getAgentId());
            t.setDeptId(pAgent.getDeptId());
            t.setSelfAmount(new BigDecimal("0.00"));
            t.setSelfTran(new BigDecimal("0.00"));
            t.setTeamAmount(pidBenefit);
            t.setTeamTran(info.getAmount());
            t.setAllAmount(pidBenefit);
            t.setAllTran(info.getAmount());
            t.setBenefitDate(info.getTransactionDate());
            t.setCreateDate(new Date());
            baseMapper.insert(t);
        } else {
            //如果为空
            if (t.getTeamAmount() == null) {
                t.setTeamAmount(new BigDecimal("0.00"));
            }

            BigDecimal teamAmount = t.getTeamAmount().add(pidBenefit);
            BigDecimal teamTran = t.getTeamTran().add(info.getAmount());
            BigDecimal allAmount = t.getAllAmount().add(pidBenefit);
            BigDecimal allTran = t.getAllTran().add(info.getAmount());
            t.setTeamAmount(teamAmount);
            t.setTeamTran(teamTran);
            t.setAllAmount(allAmount);
            t.setAllTran(allTran);
            //更新
            baseMapper.updatebenefitDay(t);
        }
        benefitInfoService.addBenefitInfo(info, pidBenefit, pAgent, t.getBenefitId());
    }

    @Override
    public void downLoad(Long deptId, HttpServletResponse response) {
        Map<String, Object> params;
        if (redisUtil.hasKey("benefitDown")) {
            params = (Map<String, Object>) redisUtil.get("benefitDown");
            params.remove("limit");
            params.remove("start");
        } else {
            params = new HashMap<>(1);
            params.put("deptId", deptId);
        }

        List<Map<String, Object>> list = baseMapper.queryListByAgentId(params);

        String fileName = "分润列表" + System.currentTimeMillis() + ".xlsx";
        String[] title = {"分润id", "姓名", "联系方式", "分润时间", "总交易", "总分润", "个人交易", "个人分润", "团队交易", "团队分润"};
        String sheetName = "终端信息表";

        String[][] content = new String[list.size()][];

        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            Map<String, Object> obj = list.get(i);
            content[i][0] = obj.get("benefitId").toString();
            content[i][1] = obj.get("name").toString();
            content[i][2] = obj.get("phone").toString();
            content[i][3] = obj.get("benefitDate").toString();
            content[i][4] = obj.get("allTran").toString();
            content[i][5] = obj.get("allAmount").toString();
            content[i][6] = obj.get("selfTran").toString();
            content[i][7] = obj.get("selfAmount").toString();
            content[i][8] = obj.get("teamTran").toString();
            content[i][9] = obj.get("teamAmount").toString();

        }
        Workbook workbook = ExcelUtil.generateNewWorkbook(sheetName, title, content);
        ExcelUtil.downLoadByExcel(response, fileName, workbook);

    }

    @Override
    public List<TranBenefitDay> queryPushFlowAccount(String benefitDateStr, Long deptId) {
        return baseMapper.queryPushFlowAccount(benefitDateStr, deptId);
    }

    @Override
    public Map<String, Object> countTotal(Map<String, Object> q) {
        Object startDate = q.get("startDate");
        Object endDate = q.get("endDate");
        if (startDate == null || "".equals(startDate)) {
            q.put("startDate", null);
        }
        if (endDate == null || "".equals(endDate)) {
            q.put("endDate", null);
        }
        List<Map<String, Object>> list = baseMapper.queryListByAgentId(q);

        BigDecimal allAmount = list.stream().map(e -> new BigDecimal(e.get("allAmount").toString())).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal selfAmount = list.stream().map(e -> new BigDecimal(e.get("selfAmount").toString())).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal teamAmount = list.stream().map(e -> new BigDecimal(e.get("teamAmount").toString())).reduce(BigDecimal.ZERO, BigDecimal::add);

        Map<String, Object> result = new HashMap<>(3);
        result.put("allAmount", allAmount);
        result.put("selfAmount", selfAmount);
        result.put("teamAmount", teamAmount);

        return result;
    }

    @Override
    public Map<String, Object> queryAgentIdSum(Long agentId, String s) {
        return baseMapper.queryAgentIdSum(agentId,s);
    }


}
